package dilmaj.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TextBoxBase;
import com.google.gwt.user.client.ui.Widget;

import dilmaj.shared.AreaVO;
import dilmaj.shared.StarAreaVO;
import dilmaj.shared.StarCommentVO;
import dilmaj.shared.StarEntryVO;
import dilmaj.shared.StarLanguageVO;
import dilmaj.shared.StarSourceVO;
import dilmaj.shared.StarTermVO;
import dilmaj.shared.StarUseCaseVO;

public class AddStarHandler implements ClickHandler {
	private DilmajConstants constants = GWT.create(DilmajConstants.class);
	
	private StarServiceAsync starSvc = GWT.create(StarService.class);
	private StarTablePanel owner;
	private StarEntryVO starVO;
	private TextBoxBase dataWidget;
	
	public AddStarHandler(TextBoxBase dataWidget, String title, StarTablePanel owner) {
		this.owner=owner;
		this.dataWidget=dataWidget;
		if (title.compareToIgnoreCase(constants.term())==0) {
			starVO=new StarTermVO();
		} else if (title.compareToIgnoreCase(constants.area())==0) {
			starVO=new StarAreaVO();
		} else if (title.compareToIgnoreCase(constants.source())==0) {
			starVO=new StarSourceVO();
		} else if (title.compareToIgnoreCase(constants.comment())==0) {
			starVO=new StarCommentVO();
		} else if (title.compareToIgnoreCase(constants.language())==0) {
			starVO=new StarLanguageVO();
		} else if (title.compareToIgnoreCase(constants.usecase())==0) {
			starVO=new StarUseCaseVO();
		}
	}
	
	  AsyncCallback<StarEntryVO> addStarCallback = new AsyncCallback<StarEntryVO>() {
		  public void onFailure(Throwable caught) {
		        // TODO: Do something with errors.
		  }
	
		  public void onSuccess(StarEntryVO result) {
			  DataStore.add(result);
			  owner.addRow(result);
			  DataStore.hideWait();
		  }
	  };
	
	  /*public void setStarEntry(StarEntryVO starVO) {
		this.starVO=starVO;
	}*/
	
	@Override
	public void onClick(ClickEvent event) {
		// TODO Auto-generated method stub
	    if (starSvc == null) {
		      starSvc = GWT.create(StarService.class);
		    }
		starVO.setCaption(dataWidget.getText());
		starVO.setDescription(owner.getDataDescription());
		if (DataStore.getUserid()!=-1) {
			starVO.setUserID(DataStore.getUserid());
			starVO.setUserName(DataStore.getUsername());
		}
		
		DataStore.showWait();
	    starSvc.addEntry(starVO, addStarCallback);
	}
}
